package cn.com.cifi.mars.schedled;

import cn.com.cifi.mars.bean.bo.SysLogBO;
import cn.com.cifi.mars.constant.*;
import cn.com.cifi.mars.entity.SysJob;
import cn.com.cifi.mars.service.CommonService;
import cn.com.cifi.mars.service.SupervisoryConsoleReturnDetailService;
import cn.com.cifi.mars.service.SysJobService;
import cn.com.cifi.mars.service.SysLogService;
import cn.com.cifi.mars.util.LocalDateTimeUtils;
import cn.com.cifi.mars.util.WebUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * 监控台定时任务
 * @Author: jyx
 * @Date: 2020/11/17 10:27
 */
@Slf4j
@Component
public class MonitoringConsoleTasks {

    @Autowired
    private SysLogService sysLogService;
    @Autowired
    private SysJobService sysJobService;
    @Autowired
    private SupervisoryConsoleReturnDetailService supervisoryConsoleReturnDetailService;
    @Autowired
    private CommonService commonService;
    /**
     * 每日的06点
     */
    @Scheduled(cron = "0 0 0/8 * * ?")
    public void calculateRealityCoefficient() {
    	boolean appointIP = commonService.isAppointIP();
        if (!appointIP){
            return;
        }
        SysJob job = sysJobService.selectJobByCode(Constants.ZERO_THIRTY_THREE);
        LocalDateTime start = null;
        LocalDateTime end = null;
        if (null != job) {
            Integer jobId = job.getId();
            int count = sysJobService.lockJobById(jobId);
            if (count == 1) {
                try {
                    start = LocalDateTime.now();
                    //获取当前时间的yearMonth
                    String yearMonth = LocalDateTimeUtils.getLocalMonth(LocalDateTime.now());
                    //生成监控台-回数据
                    supervisoryConsoleReturnDetailService.createReturn(yearMonth);
                    end = LocalDateTime.now();
                    saveLog("定时任务", "定时刷新监控台-回", "定时刷新监控台-回");
                } catch (Exception e) {
                    log.error("context:" + e);
                    saveLog("定时任务", "定时刷新监控台-回", e.toString());
                } finally {
                    sysJobService.resetJob(job, start, end);
                }
            } else {
                sysJobService.resetStatus(job);
            }
        }
    }


    //日志
    private boolean saveLog(String module, String title, String content) {
        SysLogBO bo = new SysLogBO();
        bo.setEvent(LogEventEnum.BROWSE);
        bo.setSource(LogSrcEnum.PC);
        String hostAddr = WebUtils.getLocalIP();
        bo.setIp(hostAddr);
        bo.setModule(module);
        bo.setTitle(title);
        bo.setContent(content);
        bo.setType(LogTypeEnum.ZERO.getKey());
        bo.setIsSuccess(IsSuccessEnum.SUCCESS.getKey());
        return sysLogService.add(bo, Constants.SYS);
    }
}
